<template>
  <!--开票审请-->
  <BasicModal title="开票审请" :width="900" :heigth="280"
              :canFullscreen="false" :centered="true" :destroyOnClose="true" :bodyStyle="{overflowY:'hidden'}"
              @register="registerModal" @ok="handleSubmit"
  >
    <a-row type="flex" :gutter="5" style="margin: 0; padding: 0">
      <a-col flex="250px" style="border: 1px #ddd solid; padding-top: 5px">
        <CustomerTree @onClick="onClick"/>
      </a-col>
      <a-col flex="620px" style="border: 1px #ddd solid; padding-top: 5px;">
        <a-form ref="registerForm" :model="model" :rules="validatorRules" >
        <a-row>
          <a-col :span="12">
            <a-form-item label="收款单位" name="dwmc" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              {{model.dwmc}}
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="归属日期:" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-month-picker v-model:value="model.invoiceDate" valueFormat="YYYY-MM" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              {{ info.zwsflx }}
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="笔数" :labelCol="labelCol" :wrapperCol="wrapperCol">
              {{ info.counts }}
            </a-form-item>
          </a-col>
          <a-col :span="12" class="red">
            <a-form-item label="金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              {{ info.je }}
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="票差" :labelCol="labelCol" :wrapperCol="wrapperCol">
              {{ info.fpce || 0.00 }}
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开票金额" name="sqje" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <a-input v-model:value="model.sqje" autocomplete="off"></a-input>
              <a-input type="hidden" v-model:value="info.businessId"/>
              <a-input type="hidden" v-model:value="info.account_ids"/>
              <a-input type="hidden" v-model:value="model.customerId"/>
              <a-input type="hidden" id="sflx" name="sflx" v-model:value="model.sflx"/>
              <a-input type="hidden" id="id" name="id" v-model:value="model.id"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="交接人" name="lxr" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <a-input type="text" v-model:value="model.lxr" autocomplete="off"/>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="userStore.getTenant == 1"> 
            <a-form-item label="开票单位" name="taxCompanyName" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <JDictSelectTag
                v-model:value="model.taxCompanyName"
                dictCode="taxCompanyName"
                placeholder=" "
                :maxTagCount="0"
                :getPopupContainer="(node) => node.parentNode"
                :dropdownStyle="{ width: '120px', overflow: 'auto' }"
                :dropdownMatchSelectWidth="false"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="申请单位" name="invoiceCompanyName" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--AutoComplete
                v-model:value="model.value"
                :options="options"
                :placeholder="placeholder"
                @select="onSelect"
                @search="onSearch"
                optionLabelProp="name"
              >
              </AutoComplete-->
              <a-input v-model:value="model.invoiceCompanyName" autocomplete="off"/>
              <a-input type="hidden" v-model:value="model.invoiceCompanyId"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="纳税人号" name="number" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input type="text" v-model:value="model.number" autocomplete="off"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <a-input type="text" id="lxdh" name="lxdh" v-model:value="model.lxdh" autocomplete="off"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input type="text" v-model:value="model.address" autocomplete="off"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input type="text" id="other" name="other" v-model:value="model.other"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开户行" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input type="text" autocomplete="off" v-model:value="model.bankname"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input type="text"  id="comments" name="comments" v-model:value="model.comments"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开户账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input type="text" autocomplete="off" v-model:value="model.bankno"/>
            </a-form-item>
          </a-col>
        </a-row>
        </a-form>
      </a-col>
    </a-row>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, watch } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { invoiceCompanyInfo, invoiceListSubmit, invoiceOrderSave } from "../types/invoice.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { useUserStore } from '/@/store/modules/user';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import CustomerTree from "/@/views/full/customer/components/CustomerTree.vue"
import moment from "dayjs";

const isUpdate = ref(true);
const { createMessage: $message } = useMessage();
const emit = defineEmits(['success', 'register']);
// 标题
const getTitle = computed(() => (!unref(isUpdate) ? '开票审请' : '编辑'));

const userStore = useUserStore();


//1、初始化表单modal--------------------------------------------------------------
let info  = reactive<any>({})
let model = reactive<any>({})
const registerForm = ref();
const labelCol   = ref<any>({ style: { width: '100px' } });
const wrapperCol = ref<any>({ span: 20 });

const validatorRules = {
  dwmc: [{ required: true, message: "不能为空!" }],
  sqje: [
    { required: true, message: "不能为空!" },
    { pattern:/^-?[1-9]+(\.\d+)?$|^-?0(\.\d+)?$|^-?[1-9]+[0-9]*(\.\d+)?$/, message: '输入的金额格式有误' },
  ],
  taxCompanyName: [{ required: true, message: "不能为空!" }],
  invoiceCompanyName: [{ required: true, message: "不能为空!" }],
  number: [{ required: true, message: "不能为空!" }],
  lxr: [{ required: true, message: "不能为空!" }],
};

/***
 * 表单赋值
 */
const [registerModal, { closeModal }] = useModalInner(async (data) => {
  clearModelInfo()
  clearCompanyInfo()
  //console.info("registerModal@@11111111", model)
  let params = {ids: data.ids, type: 'open'}
  await invoiceListSubmit(params).then((res) => {
    if (res.success) {
      let result = res.result;
      Object.assign(info, result);
      Object.assign(model, {
        dwmc: result.dwmc,
        account_ids: result.account_ids,
        customerId: result.path,
        sflx: result.sflx,
        ddlx: result.ddlx,
        invoiceDate: moment().format("YYYY-MM"),
      });
    } else {
      //$message(res.message);
    }
    console.info("registerModal@@22222222", model)
  })
  await setCompanyInfo();
});

//--左边-树----------------------------------------------------------------------
/**
 * 树节点点击事件
 * 只能选择公司一级，选择其它不赋值
 * @param treeNode
 * @returns {boolean}
 */
function onClick(treeNode) {
  //点选节点属性
  var typeVal = (Number(treeNode.type) + 1);
  // 上面有加1
  clearCompanyInfo()
  if ( typeVal == 2 ) {
    model.customerId = treeNode.id ;
    model.dwmc = treeNode.pathName;
    setCompanyInfo();
  } else {
    //model.customerId = "";
    //model.dwmc = "";
  }
}

/**公司开票信息*/
function setCompanyInfo() {
  const params = { customerId: model.customerId }
  invoiceCompanyInfo(params).then((res) => {
    if (!res || res.length <= 0) {
      //$message(res.message);
      return false;
    }
    //Object.assign(options, res.result || []);
    options.value = res.map((item, index) => ({
      id: item.id,
      value: (index + 1) + " " + item.name,
      name: item.name,
      number: item.number,
      address: item.address,
      bankno: item.bankno,
      bankname: item.bankname,
    }));
    placeholder.value = "已有对应 " + res.length + " 公司信息.."
    //console.info("setCompanyInfo@@", res, options)
  })
}

//清空开票公司信息
function clearCompanyInfo(){
  model.invoiceCompanyId   = '';
  model.invoiceCompanyName = '';
  model.value    = ''
  model.number   = '';
  model.address  = '';
  model.bankname = '';
  model.bankno   = '';

  //options.value = Object.assign(options.value, {});
  options.value = []
  placeholder.value = "无公司信息，请输入..";
}

//清空申请单信息
function clearModelInfo(){
  model.sqje     = ''
  model.lxr      = '';
  model.lxdh     = '';
  model.other    = '';
  model.comments = '';
}

//监控票差值
watch(
  () => model.sqje,
  (newVal) => {
    if (!newVal || newVal === 0) {
      return;
    }
    info.fpce = info.je - newVal
  },
  { deep: true, immediate: true }
);

/***
 * 公司开票信息组件
 */
let placeholder = ref<String>("");
const value = ref('');
const options = ref<[]>([]);

const onSearch = (text: string) => {
  //console.log('onSearch', text);
  if (text) {
    //Object.assign(this.schepost, {value: val})
    model.value = text;
    model.invoiceCompanyName = text;
  } else {
    //Object.assign(this.schepost, {id:'', value:''})
    model.value = "";
    model.invoiceCompanyName = "";
  }
  model.invoiceCompanyId = "";
  model.number = "";
  model.address = "";
  model.bankname = "";
  model.bankno = "";
};

const onSelect = (value, option) => {
  //console.log('onSelect', value, option);
  model.invoiceCompanyId = option.id;
  model.invoiceCompanyName = option.name;
  model.value = option.name;
  model.number = option.number;
  model.address = option.address;
  model.bankname = option.bankname;
  model.bankno = option.bankno;

  registerForm.value.clearValidate();
};


/***
 * 所有辅助操作，都是为了提交数据
 */
async function handleSubmit() {
  await registerForm.value.validate().then(async () => {
    try {
      //setModalProps({ confirmLoading: true });
      //提交表单
      await invoiceOrderSave(model).then((res) => {
        if (res.success) {
          closeModal();
          emit("success");
        } else {
          $message.warning(res.message);
          return false;
        }
      });
    } finally {
      //setModalProps({ confirmLoading: false });
    }
  }).catch((error: ValidateErrorEntity<any>) => {
    console.log("error", error);
  });
}

</script>

<style lang="less" scoped>
.formtable .inputxt {
  border: 1px solid #D7D7D7;
  border-radius: 3PX;
  padding: 7px 0 7px 5px;
  line-height: 14PX;
  font-size: 12px;
  display: inline-block;
  width: 200px;
}

.formtable .input_text:focus {
  border: 1px solid #06F;
  box-shadow: inset 0 1px 2px rgba(0, 102, 255, 0.3);
}

.formtable select {
  padding: 6px 2px;
  width: 155px;
}
.Validform_label {
  font-size: 12px;
  padding: 5px;
  white-space: nowrap;
}
.formtable {
  width: 100%;
  background-color: #ddd;
  align: right;
}
.formtable tr {
  background-color: #FAFAFA;
  align: right;
}
</style>
